package net.xxcl.exam.service;

import java.util.List;
import net.xxcl.exam.mapper.RoleMapper;
import net.xxcl.exam.mapper.RoleMenuMapper;
import net.xxcl.exam.pojo.Criteria;
import net.xxcl.exam.pojo.Role;
import net.xxcl.exam.pojo.RoleMenuKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional()
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    
    private static final Logger logger = LoggerFactory.getLogger(RoleService.class);

    @Transactional(readOnly = true)
    public int countByExample(Criteria example) {
        int count = this.roleMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    @Transactional(readOnly = true)
    public List<Role> selectByExample(Criteria example) {
        return this.roleMapper.selectByExample(example);
    }

    /**
     * 新增角色
     * @param role
     * @param menuIds
     * @return
     */
    public void insertRole(Role role,String menuIds){
        String[] str = menuIds.split(",");
        roleMapper.insert(role);
        //取出刚插入的角色id
        RoleMenuKey roleMenuKey = new RoleMenuKey();
        roleMenuKey.setRoleid(role.getId());
        for(String menuid:str){
            roleMenuKey.setMenuid(Integer.parseInt(menuid));
            this.roleMenuMapper.insert(roleMenuKey);
        }
    }

    /**
     * 编辑角色
     * @param role
     * @param menuIds
     * @return
     */
    public void updateRole(Role role,String menuIds){
        roleMapper.updateByPrimaryKeySelective(role);
        String[] str = menuIds.split(",");
        //把之前的删除
        roleMenuMapper.deleteByRoleId(role.getId());
        RoleMenuKey roleMenuKey = new RoleMenuKey();
        roleMenuKey.setRoleid(role.getId());
        for(String menuid:str){
            roleMenuKey.setMenuid(Integer.parseInt(menuid));
            this.roleMenuMapper.insert(roleMenuKey);
        }
    }

    /**
     * 根据角色id获取所有的菜单id，转换为字符串传到前台
     * @param id
     * @return
     */
    @Transactional(readOnly = true)
    public String getMenuIdsByRole(Integer id){
        List<Integer> list = roleMapper.selectMenuIdByRoleId(id);
        String menuIds = "";
        for(Integer menuId:list){
            menuIds += "," + menuId;
        }
        //去掉最开始那个,号
        return menuIds.substring(1);
    }

    /**
     * 删除角色
     * @param ids
     * @return
     */
    public int deleteRole(String ids) {
        String[] str = ids.split(",");
        for(String id:str){
            this.roleMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        return str.length;
    }
}